package dao;

import po.Address;
import po.User;
import utils.DBUtils;

import java.sql.*;
import java.util.ArrayList;

public class AddressDao {
    public ArrayList<Address> selectByUser(User user){
        ArrayList<Address> list = new ArrayList<Address>();
        Address address = null;
        Connection connection = DBUtils.getConn();
        String sql = "select * from tb_address where user_id =?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getPhone());
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                address = new Address();
                address.setRid(resultSet.getInt("rid"));
                address.setUserId(resultSet.getString("user_id"));
                address.setAdded(resultSet.getDate("added"));
                address.setAddress(resultSet.getString("address"));
                address.setReceiver(resultSet.getString("receiver"));
                address.setReceiverPhone(resultSet.getString("receiver_phone"));
                list.add(address);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
          if (resultSet!=null){
              try {
                  resultSet.close();
              } catch (SQLException throwables) {
                  throwables.printStackTrace();
              }
          }
          DBUtils.close(preparedStatement,connection);
        }
        return list;
    }
    public void insert(Address address){
        Connection connection = DBUtils.getConn();
        String sql = "insert into tb_address(user_id,address,added,receiver,receiver_phone) values(?,?,?,?,?)";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,address.getUserId());
            preparedStatement.setString(2,address.getAddress());
            preparedStatement.setDate(3,new Date(address.getAdded().getTime()));
            preparedStatement.setString(4,address.getReceiver());
            preparedStatement.setString(5,address.getReceiverPhone());
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtils.close(preparedStatement,connection);
        }
    }
}
